package cn.iocoder.yudao.module.xhyy.service.book;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.xhyy.controller.admin.book.vo.*;
import cn.iocoder.yudao.module.xhyy.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.xhyy.dal.mysql.book.BookMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.sypz.enums.ErrorCodeConstants.BOOK_NOT_EXISTS;

/**
 * 教材教辅 Service 实现类
 *
 * @author duanxinli
 */
@Service
@Validated
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public Integer createBook(BookSaveReqVO createReqVO) {
        // 插入
        BookDO book = BeanUtils.toBean(createReqVO, BookDO.class);
        bookMapper.insert(book);
        // 返回
        return book.getId();
    }

    @Override
    public void updateBook(BookSaveReqVO updateReqVO) {
        // 校验存在
        validateBookExists(updateReqVO.getId());
        // 更新
        BookDO updateObj = BeanUtils.toBean(updateReqVO, BookDO.class);
        bookMapper.updateById(updateObj);
    }

    @Override
    public void deleteBook(Integer id) {
        // 校验存在
        validateBookExists(id);
        // 删除
        bookMapper.deleteById(id);
    }

    private void validateBookExists(Integer id) {
        if (bookMapper.selectById(id) == null) {
            throw exception(BOOK_NOT_EXISTS);
        }
    }

    @Override
    public BookDO getBook(Integer id) {
        return bookMapper.selectById(id);
    }

    @Override
    public PageResult<BookDO> getBookPage(BookPageReqVO pageReqVO) {
        return bookMapper.selectPage(pageReqVO);
    }

}